package com.atguigu.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.ram.model.v20150501.DeleteAccessKeyRequest;
import com.aliyuncs.vod.model.v20170321.*;
import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.vod.service.VodService;
import com.atguigu.vod.util.InitObject;
import com.atguigu.vod.util.VodUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {

    @Autowired
    VodService vodService;

    //上传视频
    @PostMapping("uploadVideo")
    public R uploadVideo(MultipartFile file) {
        //返回上传视频Id
        String videoId = vodService.uploadVideo(file);

        return R.ok().data("videoId", videoId);
    }

    //根据视频id删除
    @DeleteMapping("deleteVideo/{id}")
    public R deleteVideoById(@PathVariable String id) {

        try {
            //初始化对象
            DefaultAcsClient client = InitObject.initVodClient("LTAI4GDpN8mgh8YwJ8scejSq", "DVBIxxNMSNdZ3DxWj0wTHMmUfYZtpN");
            //创建删除视频request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //向request设置视频id
            request.setVideoIds(id);
            //调用初始化对象的删除方法
            client.getAcsResponse(request);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "删除视频失败");
        }

    }

    //删除多个视频
    @DeleteMapping("deleteMoreVideo")
    public R deleteBatch(@RequestParam("videoList") List<String> videoList) {

        vodService.deleteMoreById(videoList);
        return R.ok();
    }

    //根据视频Id获取凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) {

        try {
            //创建初始化对象
            DefaultAcsClient client = InitObject.initVodClient(VodUtils.ACCESS_KEY_ID, VodUtils.ACCESS_KEY_SECRET);
            //创建获取凭证request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(id);

            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth", playAuth);
        } catch (Exception e) {
            throw new GuliException(20001, "获取凭证异常");
        }


    }

}
